<template>
  <div class="password-modify">
    <div class="form">
      <el-form ref="formRef" :model="form" label-width="auto" :rules="rules">
        <el-form-item label="新密码" prop="password1">
          <el-input v-model="form.password1" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
          <el-input v-model="form.password2" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" disabled></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <div class="captcha">
            <el-input v-model="form.captcha"></el-input>
            <el-button
              :loading="isLoading"
              type="primary"
              class="send"
              @click="sendCaptcha"
              :disabled="isCounting"
            >
              {{ isCounting ? `重新发送(${count}s)` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%" @click="onSubmit(formRef)">修改</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { getUserInfo, updatePasswordCaptcha, updatePassword } from '@/api/user'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const form = reactive({
  password1: '',
  password2: '',
  email: '',
  captcha: '',
})

const rules = {
  password1: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码不能少于6位', trigger: 'blur' },
  ],
  password2: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { min: 6, message: '密码不能少于6位', trigger: 'blur' },
  ],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
}

const count = ref(30) // 倒计时秒数
const formRef = ref(null)
const isCounting = ref(false) // 是否在倒计时中
const isLoading = ref(false)
const router = useRouter()

const queryInfo = async () => {
  const res = await getUserInfo()
  const { data } = res.data
  if (res.status === 200 || res.status === 201) {
    form.email = data.email
  }
}

const sendCaptcha = async () => {
  isLoading.value = true
  const res = await updatePasswordCaptcha(form.email)
  if (res.status === 200 || res.status === 201) {
    ElMessage.success('发送成功')
    isLoading.value = false
  } else {
    ElMessage.error(res.data.data || '系统繁忙，请稍后再试')
  }
  if (isCounting.value) return

  isCounting.value = true
  count.value = 30

  const timer = setInterval(() => {
    count.value--
    if (count.value <= 0) {
      clearInterval(timer)
      isCounting.value = false
    }
  }, 1000)
}

const onSubmit = (formRef) => {
  formRef.validate(async (valid) => {
    if (valid) {
      if (form.password1 !== form.password2) {
        ElMessage.error('两次密码不一致，请重新输入')
        formRef.resetFields()
        return
      }
      const res = await updatePassword({
        password: form.password1,
        email: form.email,
        captcha: form.captcha,
      })
      if (res.status === 200 || res.status === 201) {
        ElMessage.success('修改成功，请重新登录')
        localStorage.removeItem('access_token')
        localStorage.removeItem('user_info')
        localStorage.removeItem('refresh_token')
        router.push('/login')
      } else {
        ElMessage.error(res.data.data || '系统繁忙，请稍后再试')
      }
    }
  })
}
onMounted(() => {
  queryInfo()
})
</script>

<style lang="scss" scoped>
.password-modify {
  margin-left: 50px;
  margin-top: 50px;
  .form {
    width: 400px;
    margin: 30px;
    box-shadow: 0 0 10px #ccc;
    padding: 20px;
    .captcha {
      display: flex;
      justify-content: space-between;
      .send {
        margin-left: 20px;
      }
    }
  }
}
</style>
